#include "butterfly.h"
#include "ui_butterfly.h"
#include <QPainter>
#include <QMouseEvent>
#include <QDebug>

Butterfly::Butterfly(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Butterfly)
{
    ui->setupUi(this);
    // 窗口去边框
    setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
    // 设置窗口透明
    setAttribute(Qt::WA_TranslucentBackground);
    m_img.load(":/Images/up.png");
    setFixedSize(m_img.size());
    connect(&m_timer, &QTimer::timeout, this, &Butterfly::flyButterfly);
    // 启动定时器
    m_timer.start(100);
}

Butterfly::~Butterfly()
{
    delete ui;
}

void Butterfly::flyButterfly()
{
    m_isUp = !m_isUp;
    // 切换显示的图片
    QString path = m_isUp ? ":/Images/up.png" : ":/Images/down.png";
    m_img.load(path);
    // 刷新窗口
    update();
    // 窗口移动
    // 设置随机数种子
    qsrand(time(0));
    int x = geometry().topLeft().x() + qrand() % 20;
    int y = geometry().topLeft().y() + qrand() % 20;
    // 获取当前屏幕的大小
    // 判断下边界
    if(y >= m_deskWg.screenGeometry().bottom())
    {
        y = m_deskWg.screenGeometry().top();
    }
    // 判断右边界
    if(x >= m_deskWg.screenGeometry().right())
    {
        x = m_deskWg.screenGeometry().left();
    }
    move(x, y);
    qDebug() << x << y;
}

void Butterfly::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    p.drawPixmap(0, 0, width(), height(), m_img);
}

void Butterfly::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        // 两点相对距离 = 鼠标按下的点的坐标 - 窗口左上角坐标
        m_pt = event->globalPos() - this->geometry().topLeft();
    }
}

void Butterfly::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        // 移动窗口
        // 窗口左上角坐标 = 鼠标按下的点的坐标 - 两点相对距离
        move(event->globalPos() - m_pt);
    }
}
